<?php

namespace app\controllers;

use Yii;
use yii\rbac\Item;
use yii\rbac\Role;
use yii\rbac\Permission;
use yii\web\Controller;
use yii\web\Request;
use yii\web\Response;
use helper\SessionHelper;

class RoleController extends SecBaseController
{
    public function actionList(){
        $request = Yii::$app->request;
        $page_code = $request->get('page_code');
        
        $authManager = Yii::$app->authManager;
        try{ 
            $roles = $authManager->getRoles();;
            $data_list = array(); 
            foreach ($roles as $role) {
               $data_item = (array)$role;
               if (!empty($role->name)) {
                   $childrenItems = $authManager->getChildren($role->name);
                   $children = array();
                   foreach ($childrenItems as $item) {
                       $children[] = $item->name;
                   }
                   $data_item['children'] = $children;
               }  
               $data_list[] = $data_item;
            }
            //compose table data
            $page = array("page_code" => 1, "data_count" => count($roles), "page_size" => count($roles), "first" => 1, "last" => count($roles), "page_count" => 1, "startNum" => 0, "page_code_list" => array(1), "firstPage" => true, "lastPage" => true  );
            $title_name = array("key" => "name", "name" => "名称", "type" => "text", "editable" => 1, "intable" => 1, "sort_code" => "0", "is_must" => 1, "show_key" => null);
            $title_type = array("key" => "type", "name" => "类型", "type" => "number", "editable" => 0, "intable" => 1, "sort_code" => "1", "show_key" => null);
            $title_desc = array("key" => "description", "name" => "描述", "type" => "text", "editable" => 1, "intable" => 1, "sort_code" => "2", "show_key" => null);
            //$title_rule_name = array("key" => "rule_name", "name" => "规则名称", "type" => "text", "editable" => 1, "intable" => 1, "sort_code" => "3");
            //$title_data = array("key" => "data", "name" => "数据", "type" => "text", "editable" => 1, "intable" =>1, "sort_code" => "4");
            $title_created_at = array("key" => "createdAt", "name" => "创建时间", "type" => "time", "editable" => 0, "intable" =>1, "sort_code" => "5", "show_key" => null);
            $title_updated_at = array("key" => "updatedAt", "name" => "修改时间", "type" => "time", "editable" => 0, "intable" =>1, "sort_code" => "6", "show_key" => null);
            $title_children = array("key" => "children", "name" => "子角色或权限", "type" => "array", "customMap" => array("url" => "/basedata/rbacitems", "option_value" => "id", "option_text" => "name"), "editable" => 1, "intable" => 0, "show_key" => null);
            $column_title = array($title_name, $title_type, $title_desc, $title_children, $title_created_at, $title_updated_at);

            $data = array("data_name" => "role", "data_key" => "name", "page" => $page, "column_title" => $column_title, "data_list" => $data_list, "sort_code" => 0, "sortorder" => "desc");
            $this->return_page_values = array_merge($this->return_page_values, $data);
        }catch(\Exception $e){
            $this->return_page_values['errno'] = $e->getCode();
            $this->return_page_values['errmsg'] = $e->getMessage();
            return $this->myRenderFile('@tpl/page/error.tpl', $this->return_page_values);
        }

        //echo  json_encode($this->return_page_values);
//return;
        return $this->myRenderFile('@tpl/page/role/list.tpl', $this->return_page_values);

    }

    public function actionCreate(){
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $request = Yii::$app->request;
        $name = $request->post('name');
        $type = $request->post('type');
        $description = $request->post('description');
        //$rule_name = $request->post('rule_name');
        //$data = $request->post('data');
        $children = $request->post('children');
        
        $authManager = Yii::$app->authManager;
        if (empty($name)) {
            $this->return_page_values['errno'] = -1;
            $this->return_page_values['errmsg'] = 'role name is not specified';
            return $this->return_page_values;
        }
        $newRole = $authManager->createRole($name);
        $newRole->type = Item::TYPE_ROLE; 
        $newRole->description = $description;
        $newRole->ruleName = null;
        $newRole->data = null;
        $now = time();
        $newRole->createdAt = $now;
        $newRole->updatedAt = $now;
        try {
            $authManager->add($newRole);
        }catch(\Exception $e){
            $this->return_page_values['errno'] = -1;
            $this->return_page_values['errmsg'] = 'create role failed: '.$e->getMessage();
            return $this->return_page_values;
        }

        //add children
        if ($children != null && is_array($children)) {
            $children_array = $children;
        }else{
            $children_array = [];
        }
        try {
           foreach ($children_array as $child_name) {
	        $child = $authManager->getPermission($child_name);
	        if ($child == null) {
      		    $child = $authManager->getRole($child_name);
    	        }
	        if ($child != null) {
		    $authManager->addChild($newRole, $child);
	        }
    	    }
        }catch(\Exception $e){
            $this->return_page_values['errno'] = -1;
            $this->return_page_values['errmsg'] = 'add role child failed: '.$e->getMessage();
            return $this->return_page_values;
        }

        //$this->return_page_values['errno'] = 0;
        //return $this->return_page_values;
        $ret = array("errno" => 0);
        return $ret;
    }
    
    public function actionUpdate(){
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $request = Yii::$app->request;
        $name = $request->post('name');
        $type = $request->post('type');
        $description = $request->post('description');
        $rule_name = $request->post('rule_name');
        $data = $request->post('data');
        $children = $request->post('children');
        
        $authManager = Yii::$app->authManager;
        if (empty($name)) {
            $this->return_page_values['errno'] = -1;
            $this->return_page_values['errmsg'] = 'role name is not specified';
            return $this->return_page_values;
        }
        $newRole = $authManager->getRole($name);
        $newRole->type = Item::TYPE_ROLE; 
        $newRole->description = $description;
        $newRole->ruleName = $rule_name;
        $newRole->data = $data;
        $newRole->updatedAt = time();
        try {
            $authManager->update($name, $newRole); //use update function here
        }catch(\Exception $e){
            $this->return_page_values['errno'] = -1;
            $this->return_page_values['errmsg'] = 'update role failed: '.$e->getMessage();
            return $this->return_page_values;
        }

        //add children
        if ($children != null && is_array($children)) {
            $children_array = $children;
        }else{
            $children_array = [];
        }
        try {
           //clear children first
           if (count($authManager->getChildren($newRole->name)) > 0){
               if (!$authManager->removeChildren($newRole)) {
                   $this->return_page_values['errno'] = -1;
                   $this->return_page_values['errmsg'] = 'remove old children failed';
                   return $this->return_page_values;
               }
           }
           foreach ($children_array as $child_name) {
                if ($child_name == $newRole->name) {
                    continue;
                }
	        $child = $authManager->getPermission($child_name);
	        if ($child == null) {
      		    $child = $authManager->getRole($child_name);
    	        }
	        if ($child != null) {
		    $authManager->addChild($newRole, $child);
	        }
    	    }
        }catch(\Exception $e){
            $this->return_page_values['errno'] = -1;
            $this->return_page_values['errmsg'] = 'add role child failed: '.$e->getMessage();
            return $this->return_page_values;
        }

        //$this->return_page_values['errno'] = 0;
        //return $this->return_page_values;
        $ret = array("errno" => 0);
        return $ret;
    }

    public function actionDelete(){
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_JSON;

        $request = Yii::$app->request;
        $name = $request->get('name'); 

        $authManager = Yii::$app->authManager;
        if (empty($name)) {
            $this->return_page_values['errno'] = -1;
            $this->return_page_values['errmsg'] = 'role name is not specified';
            return $this->return_page_values;
        }

        try {
            $role = $authManager->getRole($name);
            $authManager->remove($role);
        } catch (\Exception $e) {
            $this->return_page_values['errno'] = -1;
            $this->return_page_values['errmsg'] = 'delete role child failed: '.$e->getMessage();
            return $this->return_page_values;
        }

        $ret = array("errno" => 0);
        return $ret;
        
    }
 
}
